{
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
}

unit Dispatcher;

interface

uses
  Classes, SysUtils, Scene, Transmitter, superobject, MiscUtils;

type
  TDispatcher = class
  private
    FScene: TScene;
    FTransmitter: TTransmitter;
    FChannelId: String;
  public
    constructor Create(Scene: TScene; Transmitter: TTransmitter; const ChannelId: String);
    function PerformAction(const TargetId: TShapeId; const ActionName: String;
      const Input: ISuperObject = nil): ISuperObject;

    property Scene: TScene read FScene;
  end;

implementation

{ TDispatcher }

constructor TDispatcher.Create(Scene: TScene; Transmitter: TTransmitter;
  const ChannelId: String);
begin
  inherited Create;
  FScene := Scene;
  FTransmitter := Transmitter;
  FChannelId := ChannelId;
end;

function TDispatcher.PerformAction(const TargetId: TShapeId; const ActionName: String;
  const Input: ISuperObject = nil): ISuperObject;
var
  Data: TMemoryStream;
  Res: TStream;
  Response: ISuperObject;
begin
  Data := TMemoryStream.Create;
  try
    WriteStreamString(Data, FChannelId);
    Data.WriteByte(10);

    WriteStreamString(Data, TargetId);
    Data.WriteByte(10);

    WriteStreamString(Data, ActionName);
    Data.WriteByte(10);

    if Input <> nil then
      Input.SaveTo(Data);

    Res := FTransmitter.Send(Data);
    try
      Response := SO(UTF8Decode(ReadStreamTail(Res)));
    finally
      Res.Free;
    end;
  finally
    Data.Free;
  end;

  Result := Response['result'];
  if FScene <> nil then
    FScene.ApplyDelta(Response['sceneDelta']);
end;

end.

